package com.appbee.core.server.requestfactory;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Provider;

import com.appbee.core.server.dao.BaseDAO;
import com.appbee.core.server.model.EditEntity;
import com.google.web.bindery.requestfactory.shared.Locator;

public class BaseLocator<T extends EditEntity,D extends BaseDAO<T>> extends Locator<T, Long>
{
	private static final Logger log = Logger.getLogger(BaseLocator.class.getName());
	private Provider<D> daoProvider;
	
	@Inject
	public void setDao(Provider<D> serviceProvider)
	{
		this.daoProvider = serviceProvider;
	}
	

	@Override
	public T create(Class<? extends T> clazz)
	{
	
		try
		{
			return clazz.newInstance();
		}
		catch (InstantiationException e)
		{
			log.log(Level.ALL, "Villa", e);
		}
		catch (IllegalAccessException e)
		{
			log.log(Level.ALL, "Villa", e);
		}
		return null;
	}


	@Override
	public T find(Class<? extends T> clazz, Long id)
	{
		if(id==null) return null;
		D d = daoProvider.get();
		return d.findById(id);
	}

	@Override
	public Long getId(T domainObject)
	{
		return domainObject.getId();
	}

	@Override
	public Class<Long> getIdType()
	{
		return Long.class;
	}

	@Override
	public Object getVersion(T domainObject)
	{
		return domainObject.getEditDateTime();
	}


	@Override
	public Class<T> getDomainType()
	{
		return daoProvider.get().getPersistentClass();
	}

}
